/*****************************************************************************
Description:

This program runs MDRD2 and MDRD1 pscores at the school-level
*
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

args bw

* Settings
set trace off
set tracedepth 1
set more off

forval year = 2016/2018{

	use "${cleandata}/prg_level_pscores_`bw'_ms_`year'.dta", clear

	gen sch = substr(sch_long, 3, 4)

	bys stu sch : egen offer_sch = max(offer_prg)

	bys stu sch : egen double pscore_form_md2_sch = total(pscore_form_prg)
	bys stu sch : egen double pscore_form_md1_sch = total(pscore_form_no_bw_prg)
	bys stu sch : egen double pscore_form_pnp_sch = total(pscore_form_bw_prg)

	bys stu sch : egen double pscore_freq_md2_sch = total(pscore_freq_prg)
	bys stu sch : egen double pscore_freq_md1_sch = total(pscore_freq_no_bw_prg)

	bys stu sch : egen double pscore_qbw_sch = total(pscore_qbw_prg)

	* Label variables
	la var offer_sch 			"Indicator variable = 1 if student got offer from school, 0 otherwise"
	la var pscore_form_md2_sch 	"Formula pscore for general risk (MDRD2) at school level"
	la var pscore_form_md1_sch 	"Formula pscore for risk at lottery schools (MDRD1) at school level"

	keep stu sch sch_long pscore_form_md1_sch pscore_form_md2_sch pscore_freq_md1_sch ///
			pscore_freq_md2_sch pscore_qbw_sch offer_sch pscore_form_pnp_sch
	duplicates drop
	drop if mi(stu) | mi(sch)
	isid stu sch

	rename (pscore_form_md1_sch pscore_form_md2_sch pscore_freq_md1_sch pscore_freq_md2_sch pscore_qbw_sch pscore_form_pnp_sch) ///
		   (pscore_form_md1_ pscore_form_md2_ pscore_freq_md1_ pscore_freq_md2_ pscore_qbw_ pscore_form_pnp_)

	rename offer_sch offer_

	drop sch_long

	local pscores pscore_form_md1_ pscore_form_md2_ pscore_form_pnp_ pscore_freq_md1_ pscore_freq_md2_ pscore_qbw_

	reshape wide `pscores' offer_ , i(stu) j(sch) string

	* Change missing to 0
	foreach var of var pscore* offer* {
		replace `var' = 0 if mi(`var')
	}

	isid stu
	destring stu, replace
	save "${cleandata}/school_level_pscores_`bw'_ms_`year'.dta", replace

}
